#include "thread.h"

#include "job.h"
#include "thread_pool.h"
#include "thread.h"

static bool s_stop = false;
static void* 
Routine(void* arg) {
	ThreadPool* s_pool = (ThreadPool *)arg;
	TRACE_LOG("[Thread  start]");

while(true){
	Job* job = s_pool->get_job();	
	ASSERT_NOT_NULL(job);
	if (job == EXIT_SIGN){
		goto thread_out;
	}
	else if (job == STOP_SIGN){
		s_stop = true;		
		continue;
	}
	else if (job == CONTINUE_SIGN){
		s_stop = false;
		continue;
	}
	else{
		TRACE_LOG("new job(%d) get", job);
		if (s_stop)
			TRACE_LOG("thread is stoped, job not done");
		else{
			job->work();	
			if (job->delete_after_use){
				job->release();
			}
		}
	}
}
thread_out:
	return NULL;
}
Thread::Thread(ThreadPool* pool) : _thread(-1), 
								   _pool(pool),
								   _name(""){
	
}
Thread::~Thread(){
	if ((pthread_t)-1 != _thread)
		pthread_join(_thread, NULL);
}

bool
Thread::start(THREAD_ROUTINE routine){
	if ( NULL == routine )
		pthread_create(&_thread, NULL, Routine, _pool);
	else
		pthread_create(&_thread, NULL, routine, _pool);
	return true;
}

void
Thread::yield(){
	pthread_yield();
}


void
Thread::set_name(std::string name) {
	_name = name;
}

void
Thread::set_name(const char* name) {
	_name = name;
}

std::string 
Thread::get_name(){
	return _name;
}
